//
//  JKMeViewController.m
//  Baisi
//
//  Created by albert on 16/3/13.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKMeViewController.h"
#import "JKMeCell.h"
#import "JKMeFooterView.h"
#import "JKSettingTableViewController.h"
#import "AFNetworking.h"
#import "JKLoginRegisterViewController.h"
#import "JKVideoViewController.h"
#import "JKFileExplorerManager.h"

#import "JKCircularProgressView.h"

#import "JKMediaLibraryViewController.h"

@interface JKMeViewController ()
{
    BOOL isJailbroken;
}
@end

@implementation JKMeViewController

static NSString *MeId = @"me";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    isJailbroken = [self isJailbroken];
    
    //初始化导航控制器
    [self setupNav];
    
    //设置tableView
    [self setupTableView];
}

//设置tableView
- (void)setupTableView{
    [self.tableView jk_adapt_iOS_11_scrollView];
    
    //注册cell
    [self.tableView registerClass:[JKMeCell class] forCellReuseIdentifier:MeId];
    
    //取消分割线
    //self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //调整section的header和footer
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = JKPostCellMargin;
    
    //设置footerView
    JKMeFooterView *footerView = [[JKMeFooterView alloc] initWithFrame:CGRectMake(0, 0, JKScreenW, 100)];
    self.tableView.tableFooterView = footerView;
    
    //分组样式，顶部默认有35的间距，可以重写setFrame，也可以像下面这样设置inset
    self.tableView.contentInset = UIEdgeInsetsMake(JKNavBarHeight, 0, JKTabBarHeight, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    [self getHttp];
}

//发送请求
- (void)getHttp{
    //参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = @"square";
    params[@"c"] = @"topic";
    
    //发送请求
    [[AFHTTPSessionManager manager] GET:@"http://api.budejie.com/api/api_open.php" parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        //创建方块
        [(JKMeFooterView *)self.tableView.tableFooterView createSquares:responseObject[@"square_list"]];
        [self.tableView setTableFooterView:self.tableView.tableFooterView];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

//初始化导航控制器
- (void)setupNav{
    //设置导航栏内容
    //通过initWithImage设置的UIImageView的尺寸就和图片的尺寸一样了
    self.navigationItem.title = @"我的";
    
    //设置导航栏rightBarButtonItem为自定义按钮
    UIBarButtonItem *moonItem = [UIBarButtonItem itemWithImage:@"mine-moon-icon" highImage:@"mine-moon-icon-click" target:self action:@selector(moonButtonClick)];
    UIBarButtonItem *settingItme = [UIBarButtonItem itemWithImage:@"mine-setting-icon" highImage:@"mine-setting-icon-click" target:self action:@selector(settingButtonClick)];
    self.navigationItem.rightBarButtonItems = @[settingItme, moonItem];
    
    //设置背景颜色
    self.tableView.backgroundColor = JKGlobalBgColor;
}

/**
 *  夜间模式
 */
- (void)moonButtonClick{
    JKLog(@"%s", __func__);
    
    JKCircularProgressView *progressView = [[JKCircularProgressView alloc] initWithFrame:CGRectMake(0, 0, 290, 290)];
    
    JKAlertView *alertView = [JKAlertView alertViewWithTitle:nil message:nil style:(JKAlertStylePlain)];
    
    alertView.setCustomPlainTitleView(NO, ^UIView *(JKAlertView *view) {
       
        return progressView;
    });
    
    [alertView addAction:[JKAlertAction actionWithTitle:@"取消" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
        
    }]];
    
    [alertView addAction:[JKAlertAction actionWithTitle:@"确定" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
        
    }]];
    
    [alertView show];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        progressView.progress = 0.8;
    });
}

/**
 *  设置按钮
 */
- (void)settingButtonClick{
    [self.navigationController pushViewController:[[JKSettingTableViewController alloc] initWithStyle:(UITableViewStyleGrouped)] animated:YES];
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return isJailbroken ? 5 : 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JKMeCell *cell = [tableView dequeueReusableCellWithIdentifier:MeId];
    
    if (indexPath.section == 0) {
        
        cell.imageView.image = [[UIImage imageNamed:@"defaultUserIcon"] circleImage];
        cell.textLabel.text = @"登录/注册";
        
    }else if (indexPath.section == 1) {
        
        cell.imageView.image = [UIImage imageNamed:@"offline_download"];
        cell.textLabel.text = @"视频缓存";
        
    }else if (indexPath.section == 2) {
        
        cell.imageView.image = [UIImage imageNamed:@"file_manage"];
        cell.textLabel.text = @"媒体资料";
        
    }else if (indexPath.section == 3) {
        
        cell.imageView.image = [UIImage imageNamed:@"file_manage"];
        cell.textLabel.text = @"文件管理";
        
    }else if (indexPath.section == 4) {
        
        cell.imageView.image = [UIImage imageNamed:@"file_manage"];
        cell.textLabel.text = @"系统文件管理";
    }
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        
        //alloc init默认就是加载同名的xib
        JKLoginRegisterViewController *loginRegisterVc = [[JKLoginRegisterViewController alloc] init];
        
        [self.navigationController presentViewController:loginRegisterVc animated:YES completion:nil];
    }else if (indexPath.section == 1) {
        
        JKVideoViewController *vc = [[JKVideoViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (indexPath.section == 2) {
        
        JKMediaLibraryViewController *vc = [[JKMediaLibraryViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (indexPath.section == 3) {
        
        [JKFileExplorerManager showWithViewController:self];
//        JKFileExplorerSortConfig sortConfig = {0, 0, 0};
//        [JKFileExplorerManager showWithDirectory:[NSHomeDirectory() stringByAppendingString:@"/Document"] sortConfig:sortConfig viewController:self];
    }else if (indexPath.section == 4) {
        
        JKFileExplorerSortConfig sortConfig = {0, 0, 0};
        [JKFileExplorerManager showWithDirectory:@"/" sortConfig:(sortConfig) viewController:self];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (BOOL)isJailbroken{
    
    BOOL jailbroken = NO;
    
    NSString *tipStr = nil;
    
    NSArray *jailbreak_tool_paths = @[
                                      @"/Applications/Cydia.app",
                                      @"/Library/MobileSubstrate/MobileSubstrate.dylib",
                                      @"/bin/bash",
                                      @"/usr/sbin/sshd",
                                      @"/etc/apt",
                                      @"/private/var/lib/apt/"
                                      ];
    
    for (NSString *path in jailbreak_tool_paths) {
        
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            
            jailbroken = YES;
            
            tipStr = [@"已越狱，路径存在: " stringByAppendingString:path ? path : @"null"];
            
            break;
        }
    }
    
    if (!jailbroken) {
        
        jailbroken = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://"]];
        
        tipStr = @"已越狱，cydia:// 可以打开";
    }
    
    if (!jailbroken) {
        
        char *env = printEnv();
        
        jailbroken = env != NULL;
        
        if (jailbroken) {
        
            tipStr = [NSString stringWithFormat:@"环境变量: %@", [NSString stringWithCString:env encoding:NSUTF8StringEncoding]];
        }
    }
    
    if (jailbroken) {
        
        NSLog(@"设备已越狱\n%@", tipStr);
        
        //[JKProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"设备已越狱\n%@", tipStr]];
    }
    
    return jailbroken;
}

char* printEnv(void) {
    
    char *env = getenv("DYLD_INSERT_LIBRARIES");
    NSLog(@"%s", env);
    return env;
}
@end
